package kr.co.casually;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import kr.co.casually.nmapview.NMapViewer;
import kr.co.casually.types.ArtInfoData;
import kr.co.casually.util.Utils;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ArtInfo extends Activity implements OnClickListener {

	private int mCultCode = 0;
	private String cultCode = "";
	private ImageView mArtInfo_img = null;
	private TextView mArtInfo_title = null;
	private TextView mArtInfo_time = null;
	private TextView mArtInfo_place = null;
	private TextView mArtInfo_homepage = null;
	private TextView mArtInfo_ageLimit = null;
	private TextView mArtInfo_ticket = null;
	private TextView mArtInfo_startDate = null;
	private TextView mArtInfo_endDate = null;
	private TextView mArtInfo_useFee = null;
	private TextView mArtInfo_program = null;
	private LinearLayout mArtInfo_linear = null;

	private boolean mExceptionFlag = false;

	ArtInfoData artInfoData = null;
	WaitDlg dlg = null;
	FileCache fileCache;
	ImageLoader imageLoader = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.art_info);

		Intent intent = getIntent();
		mCultCode = intent.getIntExtra("cultCode", 0);

		cultCode = mCultCode + "";

		mArtInfo_img = (ImageView) findViewById(R.id.artinfo_imageview);
		mArtInfo_title = (TextView) findViewById(R.id.artinfo_title);
		mArtInfo_time = (TextView) findViewById(R.id.artinfo_time);
		mArtInfo_place = (TextView) findViewById(R.id.artinfo_place);
		mArtInfo_homepage = (TextView) findViewById(R.id.artinfo_homepage);
		mArtInfo_ageLimit = (TextView) findViewById(R.id.artinfo_agelimit);
		mArtInfo_ticket = (TextView) findViewById(R.id.artinfo_ticket);
		mArtInfo_startDate = (TextView) findViewById(R.id.artinfo_startdate);
		mArtInfo_endDate = (TextView) findViewById(R.id.artinfo_enddate);
		mArtInfo_useFee = (TextView) findViewById(R.id.artinfo_useFee);
		mArtInfo_program = (TextView) findViewById(R.id.artinfo_program);
		mArtInfo_linear = (LinearLayout) findViewById(R.id.artinfo_liearlayout);
		mArtInfo_place.setOnClickListener(this);
		mArtInfo_linear.setOnClickListener(this);

		imageLoader = new ImageLoader(this);
		fileCache = new FileCache(this);

		dlg = new WaitDlg(ArtInfo.this, null, Utils.DIALOG_MSG);
		dlg.start();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		getArtInfo("getArtInfo", cultCode);

		if (dlg != null) {
			dlg.stop(dlg);
		}

		if (mExceptionFlag == true) {
			Toast.makeText(ArtInfo.this,
					"서버와의 통신이 원할하지 않습니다. 잠시후 다시 시도해 주시기 바랍니다. ",
					Toast.LENGTH_SHORT).show();
			mExceptionFlag = false;
			this.finish();
		}
	}


	// 공연정보 가져옴
	public void getArtInfo(String method_name, String cultCode) {

		String soap_action = "http://schemas.xmlsoap.org/soap/envelope/ArtService?wsdl/"
				+ method_name;

		Element h = new Element().createElement(Utils.NAMESPACE, "authInfo");
		Element username = new Element().createElement(Utils.NAMESPACE,
				"userId");
		username.addChild(Node.TEXT, "casually");
		h.addChild(Node.ELEMENT, username);

		Element authkey = new Element().createElement(Utils.NAMESPACE,
				"authKey");
		authkey.addChild(Node.TEXT,
				Utils.encodeBinary("0VENGN23I658W2A".getBytes()));
		h.addChild(Node.ELEMENT, authkey);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.headerOut = new Element[1];
		envelope.headerOut[0] = h;

		SoapObject request = new SoapObject(Utils.NAMESPACE, method_name);

		request.addProperty("cultCode", cultCode);

		envelope.setOutputSoapObject(request);
		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				Utils.URL);
		androidHttpTransport.debug = true;
		try {
			androidHttpTransport.call(soap_action, envelope);

			// System.out.println(androidHttpTransport.requestDump);

			SoapObject sobj = (SoapObject) envelope.bodyIn;

			artInfoData = new ArtInfoData();

			for (int i = 0; i < sobj.getPropertyCount(); i++) {
				SoapObject obj = (SoapObject) sobj.getProperty(i);

				artInfoData
						.setmMainImg(Utils.ifNull(obj.getProperty("mainImg")));
				artInfoData.setmEndDate(Utils.ifNull(obj.getProperty("time")));
				artInfoData.setmPlace(Utils.ifNull(obj.getProperty("place")));
				artInfoData.setmHomePage(Utils.ifNull(obj
						.getProperty("homepage")));
				artInfoData.setmAgeLimit(Utils.ifNull(obj
						.getProperty("agelimit")));
				artInfoData.setmTicket(Utils.ifNull(obj.getProperty("ticket")));
				artInfoData.setmTitle(Utils.ifNull(obj.getProperty("title")));
				artInfoData
						.setmMainImg(Utils.ifNull(obj.getProperty("mainImg")));
				artInfoData.setmStartDate(Utils.ifNull(obj
						.getProperty("startDate")));
				artInfoData
						.setmEndDate(Utils.ifNull(obj.getProperty("endDate")));
				artInfoData.setmUseFee(Utils.ifNull(obj.getProperty("useFee")));
				artInfoData
						.setmInquiry(Utils.ifNull(obj.getProperty("inquiry")));
				artInfoData
						.setmProgram(Utils.ifNull(obj.getProperty("program")));

			}

		} catch (Exception e) {

		} finally {
			setUi(artInfoData);
		}
	}

	public void setUi(ArtInfoData artInfoData) {

		if (artInfoData != null) {
			mArtInfo_title.setText(Utils.changeToHtml(artInfoData.getmTitle()));
			mArtInfo_time.setText(artInfoData.getmTime());
			mArtInfo_place.setText(artInfoData.getmPlace());
			mArtInfo_homepage.setText(artInfoData.getmHomePage());
			mArtInfo_ageLimit.setText(artInfoData.getmAgeLimit());
			mArtInfo_ticket.setText(artInfoData.getmTicket());
			mArtInfo_startDate.setText(artInfoData.getmStartDate());
			mArtInfo_endDate.setText(artInfoData.getmEndDate());
			mArtInfo_useFee.setText(artInfoData.getmUseFee());
			mArtInfo_program.setText(Utils.changeToHtml(artInfoData
					.getmProgram()));

			// url로 이미지 받아옴
			if (!Utils.isEmpty(artInfoData.getmMainImg())) {
				// 한글 주소 인코딩
				try {
					String path = artInfoData.getmMainImg().substring(0,
							artInfoData.getmMainImg().lastIndexOf("/") + 1);
					String imageName = artInfoData.getmMainImg().substring(
							artInfoData.getmMainImg().lastIndexOf("/") + 1);
					imageName = URLEncoder.encode(imageName, "euc-kr");
					String imgUrl = path + imageName;
					MainActivity.imageLoader.DisplayImage(artInfoData.getmMainImg(), this, mArtInfo_img);
//					mArtInfo_img.setImageBitmap(getBitmap(imgUrl));

				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

			} else {
				mArtInfo_img.setImageResource(R.drawable.stub);
			}
		} else {
			Toast.makeText(ArtInfo.this,
					"서버와의 통신이 원할하지 않습니다. 잠시후 다시 시도해 주시기 바랍니다. ",
					Toast.LENGTH_SHORT).show();
		}

	}

	public Bitmap getBitmap(String url) {
		File f = fileCache.getFile(url);

		// from SD cache
		Bitmap b = decodeFile(f);
		if (b != null)
			return b;

		// from web
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			Utils.CopyStream(is, os);
			os.close();
			bitmap = decodeFile(f);

			return bitmap;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	// decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;

			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale = 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;

			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	@Override
	protected void onDestroy() {
		fileCache.clear();
		super.onDestroy();
	}

	private String encoder(String str) {
		String encodedStr = "";
		try {
			encodedStr = URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodedStr;
	}

	private void startMap(String addr, String locName) {
		if (addr != null) {
			if (!addr.equals("")) {
				
				Intent locationIntent = new Intent(this, NMapViewer.class);
				locationIntent.putExtra("addr", addr);
				locationIntent.putExtra("loc_name", locName);
				locationIntent.putExtra("enAddr", encoder(addr));
				startActivity(locationIntent);
//				String uri = "http://maps.google.co.kr/maps?q="+addr;
//				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
//				intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
//				startActivity(intent);
			} else {
				Toast.makeText(ArtInfo.this, "해당정보에 주소가 없습니다.", 1000).show();
			}

		} else {
			Toast.makeText(ArtInfo.this, "해당정보에 주소가 없습니다.", 1000).show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.artinfo_place:
			startMap(artInfoData.getmPlace(), artInfoData.getmTitle());
			break;
		case R.id.artinfo_liearlayout:
			if (artInfoData != null) {
				if (!Utils.isEmpty(artInfoData.getmMainImg())) {
					Intent i = new Intent(Intent.ACTION_VIEW);
					Uri u = Uri.parse(artInfoData.getmMainImg());
					i.setData(u);
					startActivity(i);
				}
			}
			break;
		default:
			break;
		}
	}

}
